import axios from "axios";
import { BASE_URL } from "../config/http.js";

export function login(account, password) {
  return axios
    .post(`${BASE_URL}/api/user/login`, { account, password })
    .then((resp) => {
      if (resp.data && resp.data.message) {
        // 登录成功后存储 user._id 到 sessionStorage
        sessionStorage.setItem("user_id", resp.data.user._id);
        sessionStorage.setItem("token", resp.data.token);
        return resp.data;
      } else {
        throw resp.data;
      }
    })
    .catch((err) => {
      if (err.response && err.response.data) {
        throw err.response.data;
      } else {
        throw { error: "网络错误" };
      }
    });
}
